package com.yuba.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuba.common.ai.domain.VectorData;
import com.yuba.common.ai.events.GetVectorDataEvent;
import com.yuba.common.ai.events.UpdateVectorDataEvent;
import com.yuba.common.core.constant.UserConstants;
import com.yuba.common.core.utils.MapstructUtils;
import com.yuba.common.core.utils.StringUtils;
import com.yuba.common.mybatis.core.page.PageQuery;
import com.yuba.common.mybatis.core.page.TableDataInfo;
import com.yuba.front.domain.Articles;
import com.yuba.front.domain.bo.ArticlesBo;
import com.yuba.front.domain.vo.ArticlesVo;
import com.yuba.front.mapper.ArticlesMapper;
import com.yuba.front.service.IArticlesService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 钓鱼知识库Service业务层处理
 *
 * @author modakai
 * @date 2024-12-13
 */
@RequiredArgsConstructor
@Service
public class ArticlesServiceImpl implements IArticlesService {

    private final ArticlesMapper baseMapper;

    /**
     * 查询钓鱼知识库
     *
     * @param articleId 主键
     * @return 钓鱼知识库
     */
    @Override
    public ArticlesVo queryById(Long articleId){
        return baseMapper.selectVoById(articleId);
    }

    /**
     * 分页查询钓鱼知识库列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 钓鱼知识库分页列表
     */
    @Override
    public TableDataInfo<ArticlesVo> queryPageList(ArticlesBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Articles> lqw = buildQueryWrapper(bo);
        Page<ArticlesVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的钓鱼知识库列表
     *
     * @param bo 查询条件
     * @return 钓鱼知识库列表
     */
    @Override
    public List<ArticlesVo> queryList(ArticlesBo bo) {
        LambdaQueryWrapper<Articles> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Articles> buildQueryWrapper(ArticlesBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Articles> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), Articles::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getCategoryCode()), Articles::getCategoryCode, bo.getCategoryCode());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), Articles::getContent, bo.getContent());
        lqw.eq(bo.getViews() != null, Articles::getViews, bo.getViews());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), Articles::getDescription, bo.getDescription());
        return lqw;
    }

    /**
     * 新增钓鱼知识库
     *
     * @param bo 钓鱼知识库
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ArticlesBo bo) {
        Articles add = MapstructUtils.convert(bo, Articles.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setArticleId(add.getArticleId());
        }
        return flag;
    }

    /**
     * 修改钓鱼知识库
     *
     * @param bo 钓鱼知识库
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ArticlesBo bo) {
        Articles update = MapstructUtils.convert(bo, Articles.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Articles entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除钓鱼知识库信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<ArticlesVo> queryHotList(String categoryCode) {

        // 标题，分类code，浏览量
        return baseMapper.selectHotList(categoryCode);
    }

    @Override
    public void views(Long id) {
        ArticlesVo articlesVo = queryById(id);

        ArticlesBo articlesBo = new ArticlesBo();
        articlesBo.setViews(articlesVo.getViews() + 1);
        articlesBo.setArticleId(id);

        updateByBo(articlesBo);
    }

    @EventListener
    public void getArticlesNoSyncList(GetVectorDataEvent getVectorDataEvent) {
        List<VectorData> articlesVoList = baseMapper.selectVoSync();
        // 去除html内容
        // 使用示例
        for (VectorData vectorData : articlesVoList) {
            String cleanContent = cleanHtmlContent(vectorData.getContent());
            vectorData.setContent(cleanContent);
        }

        // 返回数据
        getVectorDataEvent.setData(articlesVoList);
    }

    @EventListener
    public void updateArticleSyncFlag(UpdateVectorDataEvent event) {
        List<VectorData> vectorData = event.getData();
        LambdaUpdateWrapper<Articles> updateWrapper = new LambdaUpdateWrapper<Articles>()
            .in(Articles::getArticleId, vectorData.stream().map(VectorData::getId).collect(Collectors.toList()))
            .set(Articles::getVectorSyncFlag, UserConstants.YES);
        int update = baseMapper.update(updateWrapper);
    }

    private String cleanHtmlContent(String htmlStr) {
        if (StringUtils.isBlank(htmlStr)) {
            return "";
        }

        // 定义所有需要替换的正则表达式
        final String[] REGEX_PATTERNS = {
            "<script[^>]*?>[\\s\\S]*?<\\/script>",  // script标签及内容
            "<style[^>]*?>[\\s\\S]*?<\\/style>",    // style标签及内容
            "<[^>]+>",                              // HTML标签
            "\\s*|\t|\r|\n",                       // 空白字符
            "&nbsp;?",                             // &nbsp; 和 &nbsp
            "\\s+"                                 // 连续空格
        };

        String cleanContent = htmlStr;
        // 依次执行所有替换
        for (String pattern : REGEX_PATTERNS) {
            cleanContent = cleanContent.replaceAll(pattern, "");
        }

        return cleanContent.trim();
    }
}
